package com.itcm.manage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itcm.manage.common.utils.JwtTokenUtil;
import com.itcm.manage.entity.SysPermission;
import com.itcm.manage.entity.SysUser;
import com.itcm.manage.entity.dto.SysUserDetails;
import com.itcm.manage.mapper.SysUserMapper;
import com.itcm.manage.service.SysPermissionService;
import com.itcm.manage.service.SysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 后台用户表 服务实现类
 * </p>
 *
 * @author sky
 * @since 2020-06-17
 */
@Service
@Slf4j
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService, UserDetailsService {

    @Autowired
    private SysPermissionService sysPermissionService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public SysUser getSysUserByusername(String username) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<SysUser>();
        queryWrapper.eq("username",username);
        List<SysUser> sysUsers = this.baseMapper.selectList(queryWrapper);
        if(sysUsers != null && sysUsers.size()>0){
            return sysUsers.get(0);
        }
        return null;
    }

    @Override
    public SysUser register(SysUser user) {
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(user,sysUser);
        sysUser.setCreateTime(new Date());
        sysUser.setStatus(1);
        SysUser sysUserByusername = getSysUserByusername(user.getUsername());
        if (sysUserByusername != null){
            return null;
        }
        String password = passwordEncoder.encode(sysUser.getPassword());
        sysUser.setPassword(password);
        int insert = this.baseMapper.insert(sysUser);
        if(insert>0){
            return sysUser;
        }else {
            return null;
        }
    }

    @Override
    public String login(String username, String password) {
        String token = null;
        try {
            UserDetails userDetails = loadUserByUsername(username);
            if(!passwordEncoder.matches(password,userDetails.getPassword())){
                throw new BadCredentialsException("密码错误");
            }
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            token = jwtTokenUtil.generateToken(userDetails);
        }catch (Exception e){
            log.warn("登录异常:{}",e.getMessage());
        }
        return token;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = getSysUserByusername(username);
        if (user != null) {
            List<SysPermission> permissionList = sysPermissionService.getPermissionsByUserId(user.getId());
            return new SysUserDetails(user,permissionList);
        }
        throw new UsernameNotFoundException("用户名或密码错误");
    }
}
